<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Pc_Api_V2_Promo extends Controller_Pc_Api_v2_Base
{
    // 数据请求结果
    private $result;

    /**
     * 参数验证对象
     * @var Request_Api_V2_Promo
     */
    private $validation;

    /**
     * 推广服务
     * @var Service_Api_Promo
     */
    private $service;

    public function before()
    {
        parent::before();

        // 验证
        $this->validation = Request_Api_V2_Factory::create('promo', $this->request_params);

        // 服务
        $this->service = new Service_Api_Promo();

        // 返回数据
        $this->result = array('status' => true, 'msg' => '操作成功', 'data' => array());
    }

    /**
     * @return void
     * 获取首页挂件信息
     */
    public function action_pendant()
    {
        try {
            $res = $this->service->pendant_data();

            $this->result['data'] = $res;
        } catch (Exception $e) {
            $this->result['status'] = false;
            $this->result['msg'] = $e->getMessage();
        }
    }

    public function action_promo_list()
    {
        try {
            $this->validation->promo_list()->check();

            $list = $this->service->promo_list($this->request_params);

            $this->result['data'] = $list;
        } catch (Exception $e) {
            $this->result['status'] = false;
            $this->result['msg'] = $e->getMessage();
        }
    }

    public function action_frequency_record()
    {
        try {
            $this->validation->frequency_record()->check();

            $this->service->frequency_record($this->request_params);
        } catch (Exception $e) {
            $this->result['status'] = false;
            $this->result['msg'] = $e->getMessage();
        }
    }

    public function action_coupon_receive()
    {
        $db = Database::instance();
        $db->begin();
        try {
            $this->validation->frequency_record()->check();

            $this->service->coupon_receive($this->request_params);

            $this->result['msg'] = '领取成功';
            $db->commit();
        } catch (Exception $e) {
            $db->rollback();
            $this->result['status'] = false;
            $this->result['msg'] = $e->getMessage();
        }
    }

    public function after()
    {
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }
}